package com.scientificInfo.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.Date;

@Data
@Component
public class JwtUtils {
    private long expiredTime = 10800; //3个小时后过期

    private String secret = "abcdefghijklmnopqrstuvwxyzqwerty"; // 32位的字符串密钥

    //生成jwt
    public String generateToken(String username) {

        return Jwts.builder()
                .setHeaderParam("type", "JWT") //头部信息
                .setSubject(username) //主体
                .setIssuedAt(new Date()) //发行时间
                .setExpiration(new Date(new Date().getTime() + 1000 * expiredTime))//过期时间
                .signWith(SignatureAlgorithm.HS512, secret) //签名算法
                .compact();
    }

    //解析jwt
    public Claims getClaimByToken(String jwt) {
        try {
            return Jwts.parser()
                    .setSigningKey(secret)
                    .parseClaimsJws(jwt)
                    .getBody();
        } catch (Exception e) {
            return null;
        }
    }

    //判断jwt是否过期
    public boolean isTokenExpired(Claims claims) {
        return claims.getExpiration().before(new Date());
    }
}
